# -*- coding:utf-8 -*-

#############################
###主要目的:获取全国所有的站点信息

###web url：
###获取站点信息：https://kyfw.12306.cn/otn/resources/js/framework/station_name.js
#############################

import re
import urllib.request
from src.main.station.stationObj import StationObj
from src.main.xls_util.ExcelWriter import writeExcel_first
import time
import os
import os.path
import json
from prettytable import PrettyTable
from colorama import Fore

def generate_station_list():
    url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js'
    # 发送get请求，不判断证书
    response = urllib.request.urlopen(url).read()
    # 　使用正则表达式提取所有的站点：汉字和大写代号
    # print(response.decode("utf-8"))

    pat = "([\u4e00-\u9fa5]+)\|([A-Z]+)\|([a-z]+)\|([a-z]+)\|([\d]+)"

    station_body = re.compile(pat).findall(response.decode("utf-8"))

    print("     一共有"+str(len(station_body))+"条记录")
    station_list = list()
    for index in range(len(station_body)):
        stationObj=StationObj()
        stationObj.name=station_body[index][0]
        stationObj.key = station_body[index][1]
        stationObj.pinyin = station_body[index][2]
        stationObj.short_pinyin = station_body[index][3]
        stationObj.code = station_body[index][4]
        station_list.append(stationObj)
    return station_list

def load_station_into_xls(filename):
    # 记录开始执行时间
    start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    start_detail_time=time.time()

    #filename="station_msg_info_"+time.strftime("%Y%m%d%H%M%S", time.localtime())+".xls"

    print("1.开始解析网页，记录时间"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    station_body_list=generate_station_list()

    # for i in range(len(station_body_list)):
    #     print(station_body_list[i])

    print("2.开始导出到excel，记录时间" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    if (os.path.exists(filename)):
        os.remove(filename)

    writeExcel_first(station_body_list,filename)

    end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    end_detail_time = time.time()

    print("3.程序结束.开始时间：" + start_time + "~结束时间：" + end_time)
    print('截止到导出实际一共耗时：' + str(end_detail_time - start_detail_time) + 's')

def load_station_into_txt(filename):
    url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js'
    # 发送get请求，不判断证书
    response = urllib.request.urlopen(url).read()
    outfile_opener = open(filename, 'a+', encoding="utf-8")
    outfile_opener.write(response.decode("utf-8"))
    outfile_opener.close()
    print("站点文件保存成功")

def validate_input_msg(from_station,to_station,station_file_content):
    # 　使用正则表达式提取所有的站点：汉字和大写代号
    pat_from = from_station + "\|([A-Z]+)\|"
    pat_to=to_station + "\|([A-Z]+)\|"
    key_from_body = re.compile(pat_from).findall(station_file_content)
    key_to_body = re.compile(pat_to).findall(station_file_content)

    if(len(key_from_body)!=0 and len(key_to_body)!=0):
        return True
    elif(len(key_from_body)==0 or len(key_to_body)==0):
        if(len(key_from_body)==0):
            print("开始站点输入有误，无法匹配，请重新输入后执行")
        if (len(key_to_body) == 0):
            print("结束站点输入有误，无法匹配，请重新输入后执行")
        return False
    else:
        print("验证输入信息程序有误，请联系管理员")

def get_name(key,station_file_content):
    pat = "([\u4e00-\u9fa5]+)\|"+key+"\|"
    key_body = re.compile(pat).findall(station_file_content)
    return key_body[0]
    name_body = re.compile(pat).findall()
    return name_body[0]


def get_key(name,station_file_content):
    # 　使用正则表达式提取所有的站点：汉字和大写代号
    pat = name + "\|([A-Z]+)\|"
    key_body = re.compile(pat).findall(station_file_content)
    return key_body[0]

def generate_query_body(from_station,to_station,date,stationfile_content):
    url = ('https://kyfw.12306.cn/otn/leftTicket/queryZ?'
           'leftTicketDTO.train_date={}&'
           'leftTicketDTO.from_station={}&'
           'leftTicketDTO.to_station={}&'
           'purpose_codes=ADULT').format(date, get_key(from_station, stationfile_content),
                                         get_key(to_station, stationfile_content))

    #print(url)
    return urllib.request.urlopen(url).read().decode("utf-8")

def generate_preform_msg(request_data_body,stationfile_content):
    if (request_data_body == ''):
        print("没有请求到数据，请重试")
    else:
        try:
            request_data_json = json.loads(request_data_body)
            # print(request_data_json)
            # print(type(request_data_json))
            raw_trains = request_data_json['data']['result']
            # print(raw_trains)
            pt = PrettyTable()
            pt._set_field_names("车次　车站　时间　经历时　一等座　二等座　软卧　硬卧 硬座　无座".split())
            for raw_train in raw_trains:
                # split切割之后得到的是一个列表
                data_list = raw_train.split("|")
                train_no = data_list[3]
                initial = train_no[0].lower()
                # print(train_no[0])
                # 判断是否是查询特定车次的信息
                # if not options or initial in options:
                from_station_code = data_list[6]
                to_station_code = data_list[7]
                from_station_name = ''
                to_station_name = ''
                start_time = data_list[8]
                arrive_time = data_list[9]
                time_duration = data_list[10]
                first_class_seat = data_list[31] or "--"
                second_class_seat = data_list[30] or "--"
                soft_sleep = data_list[23] or "--"
                hard_sleep = data_list[28] or "--"
                hard_seat = data_list[29] or "--"
                no_seat = data_list[33] or "--"

                pt.add_row([
                    # 对特定文字添加颜色
                    train_no,
                    '\n'.join([Fore.GREEN + get_name(from_station_code, stationfile_content) + Fore.RESET,
                               Fore.RED + get_name(to_station_code, stationfile_content) + Fore.RESET]),
                    '\n'.join([Fore.GREEN + start_time + Fore.RESET, Fore.RED + arrive_time + Fore.RESET]),
                    time_duration,
                    first_class_seat,
                    second_class_seat,
                    soft_sleep,
                    hard_sleep,
                    hard_seat,
                    no_seat
                ])
            print(pt)
        except:
            raise
